<template>
  <div>
    <a-card :style="{ marginBottom: '24px' }">
      <a-form-model ref="form" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <div class="flex">
          <a-form-model-item prop="StatisticsDateType">
            <a-select default-value="初步协议日期" class="length mr-2" v-model="form.StatisticsDateType">
              <a-select-option :value="1">
                初步协议日期
              </a-select-option>
              <a-select-option :value="2">
                初次放款日期
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-button
            v-for="(list, index) in leftPart"
            :key="index"
            class="mr-2"
            @click="durationChange(index)"
            :class="{ liBackground: changeLeftBackground == index }"
            >{{ list.name }}</a-button
          >
          <a-range-picker @change="Onchange" v-model="dateRange" />
        </div>

        <div class="flex">
          <p class="mr-2">货币：{{ form.currency }}</p>
          <span>贷款期限：</span>
          <a-input v-model="form.duration" class="length mr-2" />
          <a-select v-model="form.durationUnit" class="length mr-2">
            <a-select-option :value="2">
              月
            </a-select-option>
            <a-select-option :value="3">
              年
            </a-select-option>
          </a-select>
          <span>贷款顾问：</span>
          <a-select class="length mr-2" v-if="currentUser.role.dataPermission == 0" v-model="form.filterSysUserId">
            <a-select-option :value="item.value" v-for="item in sysList" :key="item.value">
              {{ item.text }}
            </a-select-option>
          </a-select>
          <a-select class="length mr-2" v-else v-model="currentUser.id" disabled>
            <a-select-option :value="item.value" v-for="item in sysList" :key="item.value">
              {{ item.text }}
            </a-select-option>
          </a-select>
          <span>项目状态：</span>
          <a-select v-model="form.projectStage" class="length mr-2">
            <a-select-option :value="0">
              全部
            </a-select-option>
            <a-select-option :value="8">
              进行中
            </a-select-option>
            <a-select-option :value="9">
              已完成
            </a-select-option>
          </a-select>
        </div>
        <br />
        <div class="flex">
          <span>本金额度：</span>
          <a-input class="length" v-model="form.addAllPrincipalGte" />——<a-input
            class="length mr-2"
            v-model="form.addAllPrincipalLte"
          />
          <a-button type="primary" class="left" @click="search">查询</a-button>
          <a-button class="left" @click="reset">重置</a-button>
          <span class="ml-4">货币换算：</span>
          <a-checkbox v-model="form.USD" @change="getData">
            USD
          </a-checkbox>
        </div>
      </a-form-model>
    </a-card>
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card title="项目数" :total="count">
          <a-tooltip title="项目详情" slot="action">
            <Projects :projectIds="projectIds" />
          </a-tooltip>
          <mini-area />
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :title="`贷款总额(${form.USD ? 'USD' : 'NZD'})`" :total="minMoney(addAllLoan)">
          <div>
            <mini-area />
          </div>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :title="`承诺本金额(${form.USD ? 'USD' : 'NZD'})`" :total="minMoney(addAllPrincipal)">
          <div>
            <mini-area />
          </div>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :title="`贷款余额(${form.USD ? 'USD' : 'NZD'})`" :total="minMoney(balance)">
          <mini-area />
        </chart-card>
      </a-col>
    </a-row>
    <a-card :style="{ marginBottom: '24px' }">
      <p class="info">数据统计</p>
      <div class="grid grid-cols-5">
        <div class="text">{{ `${(projectPercent * 100).toFixed(2)}%` }}</div>
        <div class="text">{{ minMoney(avgLoan) }}</div>
        <div class="text">{{ `${minMoney(avgDuration)}月` }}</div>
        <div class="text">{{ `${minMoney(avgIRR)}%` }}</div>
        <div class="text">{{ `${minMoney(avgLVR)}%` }}</div>
      </div>
      <div class="grid grid-cols-5">
        <div class="minText">项目数/总项目数</div>
        <div class="minText">{{ `平均贷款金额(${form.USD ? 'USD' : 'NZD'})` }}</div>
        <div class="minText">平均贷款期限</div>
        <div class="minText">IRR</div>
        <div class="minText">LVR</div>
      </div>
    </a-card>
    <LineChart />
    <div class="flex justify-between items-stretch">
      <div v-action:update class="mr-5 self-stretch " :style="{ marginBottom: '24px', width: '500px' }">
        <AnnualTarget />
      </div>
      <div class="flex-grow">
        <Calc />
      </div>
    </div>
    <div class="flex justify-between items-stretch">
      <div class="mr-5 self-stretch " :style="{ marginBottom: '24px', width: '300px' }">
        <CashFlow />
      </div>
      <div class="flex-grow">
        <Repay />
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { ChartCard, MiniArea } from '@/components'
import { getSysUser, getStatistics } from '@/api/common'
import form from '@/locales/lang/en-US/form'
export default {
  name: 'Analysis',
  components: {
    ChartCard,
    MiniArea,
    LineChart: () => import('./LineChart.vue'),
    AnnualTarget: () => import('./AnnualTarget.vue'),
    Calc: () => import('./Calc.vue'),
    CashFlow: () => import('./CashFlow.vue'),
    Repay: () => import('./Repay.vue'),
    Projects: () => import('./com/projects.vue')
  },
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      leftPart: [{ name: '近一周' }, { name: '近一个月' }, { name: '近三月' }, { name: '近一年' }],
      changeLeftBackground: 0,
      dateRange: [null, null],
      sysList: [],
      form: {
        StatisticsDateType: 1,
        startTime: '',
        endTime: '',
        currency: 'NZD',
        duration: '',
        durationUnit: 2,
        filterSysUserId: 999,
        projectStage: 0,
        addAllPrincipalGte: '',
        addAllPrincipalLte: '',
        USD: false
      },
      projectIds: [],
      count: 0,
      addAllLoan: 0,
      addAllPrincipal: 0,
      balance: 0,
      projectPercent: 0,
      avgLoan: 0,
      avgDuration: 0,
      avgIRR: 0,
      avgLVR: 0
    }
  },
  computed: {
    currentUser() {
      return this.$store.getters.userInfo
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      await this.getSysUsers()
      // this.form.filterSysUserId = this.currentUser.id
      await this.getData()
      this.changeLeftBackground = -1
    },
    durationChange(index) {
      this.changeLeftBackground = index
      if (index == 0) {
        this.dateRange = [moment(Date.now()).subtract(7, 'days'), moment(Date.now(), 'x')]
      }
      if (index == 1) {
        this.dateRange = [moment(Date.now()).subtract(1, 'months'), moment(Date.now(), 'x')]
      }
      if (index == 2) {
        this.dateRange = [moment(Date.now()).subtract(3, 'months'), moment(Date.now(), 'x')]
      }
      if (index == 3) {
        this.dateRange = [moment(Date.now()).subtract(1, 'years'), moment(Date.now(), 'x')]
      }
      this.getData()
    },
    Onchange() {
      this.changeLeftBackground = -1
    },
    async getSysUsers() {
      this.sysList = []
      this.sysList.push({ text: '全部', value: 999 })
      const res = await getSysUser()
      res.result.data.forEach(el => {
        this.sysList.push({ text: el.name, value: el.id })
      })
    },
    minMoney(v) {
      v = Number(v).toFixed(2)
      return `${v}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    search() {
      this.getData()
    },
    reset() {
      this.form.StatisticsDateType = 1
      this.form.duration = ''
      this.form.durationUnit = 2
      this.form.filterSysUserId = this.currentUser.role.dataPermission == 0 ? 999 : this.currentUser.id
      this.form.projectStage = 0
      this.form.addAllPrincipalGte = ''
      this.form.addAllPrincipalLte = ''
      this.form.USD = false
      this.changeLeftBackground = -1
      this.dateRange = [null, null]
      this.getData()
    },
    async getData() {
      // console.log(this.form.filterSysUserId)
      const form = Object.assign({}, this.form)
      if (this.form.StatisticsDateType) {
        form.StatisticsDateType = this.form.StatisticsDateType
      }
      if (this.dateRange[0]) {
        form.startDate = Number(this.dateRange[0].startOf('day').format('X'))
        form.endDate = Number(this.dateRange[1].startOf('day').format('X'))
      }
      if (this.form.duration) {
        form.duration = this.form.duration
        form.durationUnit = this.form.durationUnit
      } else {
        delete form.durationUnit
      }
      if (this.form.addAllPrincipalGte) {
        form.addAllPrincipalGte = this.form.addAllPrincipalGte
      }
      if (this.form.addAllPrincipalLte) {
        form.addAllPrincipalLte = this.form.addAllPrincipalLte
      }
      if (this.form.projectStage == '全部') {
        delete form.projectStage
      }
      if (this.form.filterSysUserId == 999) {
        delete form.filterSysUserId
      }
      if (this.form.USD == true) {
        form.USD = this.form.USD
      } else {
        delete form.USD
      }
      for (let k in form) {
        if (!form[k]) {
          delete form[k]
        }
      }
      const res = await getStatistics(form)
      this.count = res.result.data.count || 0
      this.addAllLoan = res.result.data.addAllLoan || 0
      this.addAllPrincipal = res.result.data.addAllPrincipal || 0
      this.balance = res.result.data.balance || 0
      this.projectPercent = res.result.data.projectPercent || 0
      this.avgLoan = res.result.data.avgLoan || 0
      this.avgDuration = res.result.data.avgDuration || 0
      this.avgIRR = res.result.data.avgIRR || 0
      this.avgLVR = res.result.data.avgLVR || 0
      this.projectIds = res.result.data.projectIds || 0
    }
  }
}
</script>

<style lang="less" scoped>
.length {
  width: 130px;
}
.liBackground {
  background: #1890ff;
  color: white;
}
.left {
  margin-left: 15px;
}
.info {
  border-left: 2px solid #1890ff;
  padding-left: 10px;
  font-size: 20px;
  // margin-left: 50px;
}
.text {
  color: #1890ff;
  font-size: 30px;
  text-align: center;
}
.minText {
  font-size: 15px;
  text-align: center;
}
.blue {
  background-color: rgb(24, 154, 238);
  border-radius: 5px;
}
</style>
